package br.ufc.vv.dao;


import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import br.ufc.vv.model.Candidato;
import br.ufc.vv.util.HibernateUtil;

public class CandidatoDao {

	public void save(Candidato candidato){
		Session session = HibernateUtil.getSession();
		Transaction transacao = session.beginTransaction();
		try {
			session.save(candidato);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
		} finally {
			session.close();
		}	
	}


	public void update(Candidato candidato){
		Session session = HibernateUtil.getSession();
		Transaction transacao = session.beginTransaction();
		try {
			session.update(candidato);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
		} finally {
			session.close();
		}	
	}

	public void delete(Candidato candidato){
		Session session = HibernateUtil.getSession();
		Transaction transacao = session.beginTransaction();
		try {
			session.delete(candidato);
			transacao.commit();
		} catch (Exception e) {
			transacao.rollback();
		} finally {
			session.close();
		}	
	}

	public List<Candidato> list(){
		Session session = HibernateUtil.getSession();
		try {
			Criteria c = session.createCriteria(Candidato.class);
			return c.list();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}

	public Candidato get(Long id) {
		Session session = HibernateUtil.getSession();
		return (Candidato) session.get(Candidato.class, id);
	}
	
	public List<Candidato> listCandidatoVotacao(Long id) {
		
		Session session = HibernateUtil.getSession();
		
		try {
			org.hibernate.Query query =  session.createQuery("Select * from Candidato where id_votacao: id");
			
			query.setLong("id", id);
			return query.list();	
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Candidato logar(Candidato candidato){
		Session session = HibernateUtil.getSession();
		try {
			Criteria c = session.createCriteria(Candidato.class);
			c.add(Restrictions.eq("nome", candidato.getNome()));
			c.add(Restrictions.eq("cpf", candidato.getCpf()));
			return (Candidato) c.uniqueResult();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}
}
